package com.yl.chainStore.control.sick

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogOperationVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailSelectVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailToStatusVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailUpdateVo
import com.yl.chainStore.pojo.vo.user.CompanyUserOperationLogSelectVo
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.chainStore.services.IWebCompanyUserService
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.services.sick.ISickMedicalRecordsService
import com.yl.chainStore.util.customerSubscribeItemToTree
import com.yl.chainStore.util.setDayFirstTime
import com.yl.chainStore.util.setDayLastTime
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*
import java.util.*
import kotlin.Exception

/**
 * 就诊记录相关记录
 */
@RestController
@RequestMapping("sick/record/")
open class CustomerRecordController(
	private val iWebCompanyDeptService: IWebCompanyDeptService,
	private val iCustomerInfoService: ICustomerInfoService,
	private val iSickMedicalRecordsService: ISickMedicalRecordsService,
	private val iWebCompanyUserService: IWebCompanyUserService,
	private val iCustomerSubscribeLogService: ICustomerSubscribeLogService,

	) : BaseCtrl() {


	/**
	 *  今日就诊记录分页
	 */
	@PostMapping("getTodayRecordPage")
//	@PermsCode("sick:record:log:list:today")
	@Transactional
	open fun getTodayRecordPage(@RequestBody vo: SickMedicalRecordsDetailSelectVo): ResponseBody {
		if (vo.day == null) {
			vo.day = Date()
		}
		vo.orderBy = "smrd.start_time"
		if (getContext().subCompanyId==549L){
			vo.orderBy = "smrd.master_user_id,smrd.start_time"
		}
		vo.notStatuses = mutableListOf()
		vo.notStatuses!!.add(Status.CANCEL)
		val medicalRecordsPage =
			iWebCompanyDeptService.getMedicalRecordsPage(
				getContext().subCompanyId,
				Page(vo.current, vo.size),
				vo
			)

		for (detail in medicalRecordsPage.records) {
			if(detail.customerId != null){
				 iCustomerInfoService.getJoinInfoByCustomerId(detail.customerId !!,detail)
			}
			if (detail.subscribeLogId != null) {
				detail.subscribeLog = iCustomerSubscribeLogService.getById(detail.subscribeLogId!!)
				if (detail.subscribeLog != null && detail.subscribeLog!!.itemIdsShow != null && detail.subscribeLog!!.itemIdsShow!!.isNotEmpty()) {
					detail.subscribeLog!!.itemNames =
						iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(detail.subscribeLog!!.itemIdsShow!!)
				}
			}
		}
		return returnSuccess(medicalRecordsPage)
	}

	/**
	 *  今日就诊记录数量
	 */
	@GetMapping("getTodayRecordCount")
	@Transactional
//	@PermsCode("sick:record:log:list:today")
	open fun getTodayRecordCount(): ResponseBody {
		val vo = SickMedicalRecordsDetailSelectVo(
			day = Date(),
		)
		vo.notStatuses = mutableListOf()
		vo.notStatuses!!.add(Status.CANCEL)
		val count =
			iWebCompanyDeptService.getMedicalRecordsCount(
				getContext().subCompanyId,
				vo
			)
		return returnSuccess(count)
	}

	/**
	 *  今日就诊记录数量(已到)
	 */
	@GetMapping("getTodayRecordComeCount")
	@Transactional
//	@PermsCode("sick:record:log:list:today")
	open fun getTodayRecordComeCount(): ResponseBody {

		val vo = SickMedicalRecordsDetailSelectVo(
			day = Date(),
			comeStatus = true
		)
		vo.notStatuses = mutableListOf()
		vo.notStatuses!!.add(Status.CANCEL)
		val count =
			iWebCompanyDeptService.getMedicalRecordsCount(
				getContext().subCompanyId,
				vo
			)
		return returnSuccess(count)
	}

	/**
	 *  今日就诊记录数量（未到）
	 */
	@GetMapping("getTodayRecordUnComeCount")
	@Transactional
//	@PermsCode("sick:record:log:list:today")
	open fun getTodayRecordUnComeCount(): ResponseBody {
		val vo = SickMedicalRecordsDetailSelectVo(
			day = Date(),
			comeStatus = false
		)
		vo.notStatuses = mutableListOf()
		vo.notStatuses!!.add(Status.CANCEL)
		val count =
			iWebCompanyDeptService.getMedicalRecordsCount(
				getContext().subCompanyId,
				vo
			)
		return returnSuccess(count)
	}


	/**
	 * 获取就诊记录（医生获取自身的）
	 */
	@PostMapping("getDoctorRecordDetailPage")
	@Transactional
//	@PermsCode("sick:record:doctor:list")
	open fun getDoctorRecordDetailPage(@RequestBody vo: SickMedicalRecordsDetailSelectVo): ResponseBody {
		if (vo.day == null) {
			vo.day = Date()
		}
    vo.orderBy = "smrd.start_time"
		val recordDetailPage = iWebCompanyUserService.getRecordDetailPage(
			getContext().userId,
			Page(vo.current, vo.size),
			vo
		)
		for (detail in recordDetailPage.records) {
			if(detail.customerId != null){
				detail.customerInfo = iCustomerInfoService.getJoinInfoByCustomerId(detail.customerId !!,detail)
			}
		}
		return returnSuccess(recordDetailPage)
	}

	/**
	 * 客户预约项目
	 */
	@GetMapping("getCustomerSubscribeItems")
	@Transactional
	open fun getCustomerSubscribeItems(): ResponseBody {
		val list = iWebCompanyDeptService.getCustomerSubscribeItemList()
		return returnSuccess(customerSubscribeItemToTree(list))
	}

	/**
	 * 某客户的明细列表
	 */
	@PostMapping("getCustomerRecordDetailPage")
	@Transactional
//	@PermsCode("customer:record:detail:list")
	open fun getCustomerRecordDetailPage(@RequestBody vo: SickMedicalRecordsDetailSelectVo): ResponseBody {
		if (vo.customerId == null) {
			return returnError(ErrorCode.PARAM_EMPTY)
		}
		val customerRecordsDetailPage = iCustomerInfoService.getCustomerRecordsDetailPage(
			Page(vo.current, vo.size),
			vo
		)
		for (detail in customerRecordsDetailPage.records) {
			if(detail.customerId != null){
				detail.customerInfo = iCustomerInfoService.getJoinInfoByCustomerId(detail.customerId !!,detail)
			}
		}
		return returnSuccess(customerRecordsDetailPage)
	}

	/**
	 * 某客户的明细列表
	 */
	@PostMapping("getCustomerRecordDetailList")
	@PermsCode("customer:record:detail:list")
	@Transactional
	open fun getCustomerRecordDetailList(@RequestBody vo: SickMedicalRecordsDetailSelectVo): ResponseBody {
		if (vo.customerId == null) {
			return returnError(ErrorCode.PARAM_EMPTY)
		}
		val customerRecordsDetailList = iCustomerInfoService.getCustomerRecordsDetailList(vo)
		for (detail in customerRecordsDetailList) {
//			if(detail.customerId != null){
//				iCustomerInfoService.getJoinInfoByCustomerId(detail.customerId !!,detail)
//			}
			if(detail.subscribeLogId != null){
				detail.subscribeLog = iCustomerSubscribeLogService.getById(detail.subscribeLogId!!)
				if (detail.subscribeLog != null && detail.subscribeLog!!.itemIdsShow != null && detail.subscribeLog!!.itemIdsShow!!.isNotEmpty()) {
					detail.subscribeLog!!.itemNames =
						iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(detail.subscribeLog!!.itemIdsShow!!)
				}
			}
		}
		return returnSuccess(customerRecordsDetailList)
	}


	/**
	 * 改变就诊记录状态
	 */
	@PostMapping("detailToStatus")
	@Transactional(rollbackFor = [Exception::class])
//	@PermsCode("sick:today:detailToStatus")
	open fun detailToStatus(@RequestBody vo: SickMedicalRecordsDetailToStatusVo): ResponseBody {
		val detailToStatus = iSickMedicalRecordsService.detailToStatus(vo)
		if (detailToStatus.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return returnSuccess()
	}

	/**
	 * 记录状态回退
	 */
	@PostMapping("backDetailToStatus/{id}")
	@Transactional(rollbackFor = [Exception::class])
//	@PermsCode("sick:today:detailToStatus")
	open fun backDetailToStatus(@PathVariable id: Long): ResponseBody {
		val backDetailStatus = iSickMedicalRecordsService.backDetailStatus(id)
		if (backDetailStatus.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return backDetailStatus
		}
		return returnSuccess()
	}


	/**
	 * 获取就诊记录明细（挂号信息）
	 */
	@GetMapping("getRecordDetailById/{id}")
	@Transactional
	open fun getRecordDetailById(@PathVariable id: Long): ResponseBody {
		return returnSuccess(iSickMedicalRecordsService.getDetailByDetailId(id))
	}

	/**
	 * 通过明细id获取预约（不是预约生成的直接返回空）
	 */
	@GetMapping("getSubLogByDetailId/{id}")
	@Transactional
	open fun getSubLogByDetailId(@PathVariable id: Long): ResponseBody {
		val detail = iSickMedicalRecordsService.getDetailByDetailId(id)
		if (detail?.subscribeLogId != null) {
			return returnSuccess(iCustomerSubscribeLogService.getById(detail.subscribeLogId!!))
		}
		return returnSuccess()
	}

	/**
	 * 修改就诊信息
	 */
	@PostMapping("updateRecordDetail")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("customer:record:detail:update")
	open fun updateRecordDetail(@RequestBody vo: SickMedicalRecordsDetailUpdateVo): ResponseBody {

		val updateDetailByDetailId = iSickMedicalRecordsService.updateDetailByDetailId(vo)
		if (updateDetailByDetailId.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return updateDetailByDetailId
		}
		val detail = iSickMedicalRecordsService.getDetailByDetailId(vo.id)

		if(detail != null){
			iCustomerSubscribeLogService.updateByRecordDetail(detail)
		}
		return returnSuccess()
	}

	/**
	 * 医生我的工作上面的统计
	 */
	@GetMapping("getDoctorWorkCount")
	@Transactional
	open fun getDoctorWorkCount(): ResponseBody {
		val userId = getContext().userId
		val resMap = mutableMapOf<String, Int>()
		val startDate = Date()
		setDayFirstTime(startDate)
		val endDate = Date()
		setDayLastTime(endDate)
		resMap["subCount"] = iWebCompanyUserService.getTodayNewAddSubCount(userId)
		resMap["historyCount"] = iWebCompanyUserService.getUpdateLogCountByVo(
			CompanyUserOperationLogSelectVo(
				createUserId = userId,
				startTime = startDate,
				endTime = endDate,
				tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_MEDICAL_HISTORY,
//				groupStr = "associated_id"
			)
		)
		resMap["visitCount"] = iWebCompanyUserService.getVisitCountToday(userId)
		return returnSuccess(resMap)
	}

	/**
	 * 查询修改日志
	 */
	@GetMapping("getDetailUpdateLogById/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun getUpdateLogById(@PathVariable id:Long):ResponseBody{
		return returnSuccess(iSickMedicalRecordsService.getRecordDetailUpdateLog(id))
	}

	@PostMapping("cancelSubscribe/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun cancelSubscribe(@PathVariable id:Long):ResponseBody{
		val cancelRecordDetail = iSickMedicalRecordsService.cancelRecordDetail(id)
		if(cancelRecordDetail.bodyIsError()){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return cancelRecordDetail
		}
		val detailByDetailId = iSickMedicalRecordsService.getDetailByDetailId(id)
		if(detailByDetailId != null){
			if(detailByDetailId.subscribeLogId != null){
				val cancelLog = iCustomerSubscribeLogService.cancelLog(CustomerSubscribeLogOperationVo(detailByDetailId.subscribeLogId!!))
				if (cancelLog.bodyIsError()) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
					return cancelLog
				}
			}
			val onlyCancelRecordDetail = iSickMedicalRecordsService.onlyCancelRecordDetail(id)
			if (onlyCancelRecordDetail.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return onlyCancelRecordDetail
			}
		}



		return returnSuccess()
	}

	/**
	 *	删除记录
	 */
	@PostMapping("delRecordDetail/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun delRecordDetail(@PathVariable id: Long):ResponseBody{
		val delDetail = iSickMedicalRecordsService.delDetail(id)
		if(delDetail.bodyIsError()){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return delDetail
	}


}
